package com.kukudb.asaproject.serveice;

import com.kukudb.asaproject.pojo.User;
import com.kukudb.asaproject.pojo.UserLicenses;
import com.kukudb.asaproject.repository.UserLicensesRepository;
import com.kukudb.asaproject.repository.UserRepository;
import com.kukudb.asaproject.serveice.interfaceTemp.UserServiceInterface;
import com.kukudb.asaproject.utils.DateUtils;
import com.kukudb.asaproject.utils.JWTUtils;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
public class UserServiceImpl implements UserServiceInterface {
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserLicensesRepository userLicensesRepository;
    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        return null;
    }

    @Override
    public User updateLastLoginTime(Integer userId) {
        User user = userRepository.selectById(userId);
        user.setLastLogin(new Date());
        userRepository.updateById(user);
        return user;
    }

    @Override
    public void addUser(User user) {
        // TODO Auto-generated method stub
        //添加用户到数据库
        try {
            user.setCreatedAt(new Date());
//            user.setUpdateTime(new Date());
            userRepository.insert(user);
            logger.info("添加用户成功{}",user);
            //初始化角色信息
            UserLicenses userLicenses = new UserLicenses();
            userLicenses.setUserId(user.getUserId());
            userLicenses.setLicenseType("1");
            userLicenses.setTotalValue(1);
            userLicenses.setUsedValue(0);
            userLicenses.setStartTime(new Date());
            userLicenses.setStatus("1");
            userLicenses.setCreateTime(new Date());
            userLicenses.setEndTime(DateUtils.parseDate("2025-6-7 23:59:59"));
            userLicenses.setUpdateTime(new Date());
            logger.info("添加用户角色信息{}",userLicenses);
            userLicensesRepository.insert(userLicenses);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("添加用户失败");
        }

    }

    @Override
    public User login(User user, HttpSession session) {
        //使用MyBatis Plus查询用户名和密码是否对应
        User loginUser = userRepository.findUserByUsernameAndPassword(user.getUserName(), user.getPassword());
        if (loginUser == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        User user1 = updateLastLoginTime(loginUser.getUserId());
        //将信息存入session
        session.setAttribute("token", JWTUtils.createToker(user1));
        session.setAttribute("user", user1);

        return user1;
    }
}
